/*
 * TODO: 1.12.2010
 *
 * START - clickable neat items,
 * IFRAME - propagation??
 * GADGETS - how to
 */

/**
 * Albireo library for operating system look-alike
 * and advanced functions
 */
var albireo = {
    /**
     * Progressbar object is used for ajax progress
     *
     * It is completely private!
     * Should use albireo.ajax.progress as alias
     * This method is an alias for jQuery getJSON
     */
    "_progressbar" : {
        "id" : 0,
        "_constructor" : function (id) {
            this.globalrequest = null;
            this.len = null;
            this.id = id;

            this.ajax = function (url, data, callback) {
                $("body").append('<div id="albireoprogressdialog'+this.id+'">'
                    +'<div id="albireoprogressdialogloader'+this.id+'"></div>'
                    +'<div id="albireoprogressdialogper'+this.id+'">&nbsp;</div>'
                    +'</div>');
                $("#albireoprogressdialog"+this.id).dialog();
                $('#albireoprogressdialogloader'+this.id).progressbar({
                    value : 0
                });
                this.globalrequest = $.getJSON(url, data, callback);
                this.registerAjax(this);
            };

            this.registerAjax = function (help) {
                function go () {
                    switch(help.globalrequest.readyState) {
                        case 0:
                        case 1:
                            $("#albireoprogressdialogper"+help.id).html("Initializing");
                            break;
                        case 2:
                            $("#albireoprogressdialogper"+help.id).html("Data sent to server");
                            break;
                        case 3:
                            $("#albireoprogressdialogper"+help.id).html("Receiving");
                            break;
                    }
                    if (!$.browser.msie) {
                        if ( help.globalrequest.responseText.length > 0) {
                            if (help.len == null || help.len == '') {
                                help.len = help.globalrequest.responseText.substring(help.globalrequest.responseText.indexOf('__size')+8,help.globalrequest.responseText.indexOf(','));
                            } else {
                                percent = Math.min(Math.floor(help.globalrequest.responseText.length*100/help.len),100);
                                $("#albireoprogressdialogper"+help.id).html( "Receiving: " + percent + " %");
                                $('#albireoprogressdialogloader'+help.id).progressbar({
                                    value : percent
                                });
                            }
                        }
                    }
                    if (help.globalrequest.readyState != 4) {
                        setTimeout(go,100);
                    } else {
                        $("#albireoprogressdialog"+help.id).dialog( "destroy" );
                        $("#albireoprogressdialog"+help.id).remove();
                    }
                }
                setTimeout(go,10);
            };
        },
        "create" : function (url, data, callback) {
            new this._constructor(this.id++).ajax(url, data, callback);
        }
    },
    ///// PROGRESS BAR DIALOG END /////
	
    /**
     * Object for ajax communication
     */
    "ajax" : {
        /**
         * Creates progressbar for ajax same use as jQuery getJSON
         */
        progress : function (url, data, callback) {
            albireo._progressbar.create(url, data, callback);
        }
    },
    ///// AJAX END /////
	
    /**
     * Object for desktop of operating system
     */
    "desktop" : {
        element : null,
        contextmenu : null,
        setElement : function (element) {
            albireo.desktop.element = element;
        },
        getElement : function () {
            return albireo.desktop.element;
        },
        getHeight : function () {
            return $(window).height()-albireo.taskbar.getElement().height();
        },
        getWidth : function () {
            return $(window).width()-4;
        },
        display : function ( url ) {
            id = albireo.desktop.getElement();
            id.width(albireo.desktop.getWidth()).height(albireo.desktop.getHeight());
            appImage = new Image ();
            appImage.onload = function() {
                  $('#desktopBackground').remove();
                  albireo.image.stretch(appImage, $(window));
                  $('<img src="'+url+'"  alt="'+url+'" width="'+innerWidth+'" height="'+innerHeight+'" id="desktopBackground" />').css({
                    position: "absolute",
                    zIndex:	-10,
                    left: 0,
                    top: 0
                }).appendTo("body");
                //props = albireo.image.resize(appImage, $(window));
                //innerWidth = props.width;
                //innerHeight = props.height;				
                //pos = albireo.image.center(innerWidth, innerHeight, $(window).width(), $(window).height() );

//                $('<img src="'+url+'"  alt="'+url+'" width="'+innerWidth+'" height="'+innerHeight+'" id="desktopBackground" />').css({
//                    position: "absolute",
//                    zIndex:	-10,
//                    left: pos.left,
//                    top: pos.top
//                }).appendTo("body");
            };
            appImage.src = url;
            //albireo.desktop.contextmenu = new albireo.contextmenu(id);
            //albireo.desktop.contextmenu.add("desktop prvni polozka", function () {
                //alert("desktop jedna");
            //});
            //albireo.desktop.contextmenu.add("desktop druha polozka", function () {
                //alert("desktop dva");
            //});
       },
		
        icons : null,
	
        createIcons : function () {
            id = albireo.desktop.getElement();
            albireo.desktop.icons = new albireo.icons(id,80,80);
            albireo.desktop.icons.setCols(Math.floor(albireo.desktop.icons.element.width()/albireo.desktop.icons.getWidth()));
            albireo.desktop.icons.setRows(Math.floor(albireo.desktop.icons.element.height()/albireo.desktop.icons.getHeight()));
            albireo.desktop.icons.create();
            albireo.desktop.icons.set(new albireo.icon(function () {
                albireo.applications.createFromUrl("Seznam","http://www.seznam.cz");
            },"http://www.macdesktops.net/core/images/user_icon_yellow.gif","Seznam"),0,0);
            albireo.desktop.icons.set(new albireo.icon(function () {
                albireo.applications.createFromUrl("Facebook","http://www.facebook.com");
            },"http://arabcrunch.com/wp-content/themes/ac-theme-evolution/evolution/images-green/facebook.png","Facebook"),0,1);
            albireo.desktop.icons.set(new albireo.icon(function () {
                albireo.applications.createFromUrl("Acrobat Reader","http://www.seznam.cz");
            },"http://www.nuh.nhs.uk/images/acrobat_icon.gif","Acrobat Reader"),0,2);
            albireo.desktop.icons.set(new albireo.icon(function () {
                albireo.applications.createFromUrl("YouTube","http://www.youtube.com");
            },"css/skins/albireosilver/YouTube32.png","YouTube"),0,3);
            albireo.desktop.icons.set(new albireo.icon(function () {
                albireo.applications.createFromUrl("G-Switch","systemApps/gswitch.html");
            },"css/skins/albireosilver/g-switch32.png","G-Switch"),0,4);
            albireo.desktop.icons.set(new albireo.icon(function () {
                albireo.applications.createFromUrl("GrooveShark","http://www.grooveshark.com");
            },"css/skins/albireosilver/GrooveShark32.png","GrooveShark"),0,5);
            
            albireo.desktop.icons.draw();

            id.mousedown(function () {
                if (!albireo.keys.ctrl) {
                    $("#" + helper.element.attr("id") + " .ui-selected").removeClass('ui-selected');
                }
            });

            id.droppable({
                accept: '.albireoicon',
                drop: function(event, ui) {
                    var icon = null;
                    var left = (id.position().left + (ui.position.left+(ui.draggable.width() / 2)) - ((ui.position.left+(ui.draggable.width() / 2)) % ui.draggable.width())) / albireo.desktop.icons.getWidth();
                    var top = (id.position().top + (ui.position.top+(ui.draggable.height() / 2)) - ((ui.position.top+(ui.draggable.height() / 2)) % ui.draggable.height())) / albireo.desktop.icons.getHeight();
                    function go() {
                        for (var i = 0; i < albireo.desktop.icons.getCols(); i++) {
                            for (var j = 0; j < albireo.desktop.icons.getRows(); j++) {
                                if (albireo.desktop.icons.get(i,j) != null && albireo.desktop.icons.get(i,j).name == ui.draggable.find('.iconName').text()) {
                                    if (i == left && j == top) {
                                        return false;
                                    }
                                    icon = albireo.desktop.icons.get(i,j);
                                    albireo.desktop.icons.set(null,i,j);
                                    return true;
                                }
                            }
                        }
                    }
                    if (!go()) {
                        return false;
                    }
                    top = Math.min(Math.ceil(top),albireo.desktop.icons.getRows()-1);
                    if (albireo.desktop.icons.get(left,top) != null) {
                        i = left;
                        j = top;
                        while (albireo.desktop.icons.get(i,j) != null) {
                            j = ++j % (albireo.desktop.icons.getRows());
                            if (j == 0) i++;
                        }
                        u = i;
                        v = j;
                        while ( i != left || j != top ) {
                            if (j == 0) {
                                v = albireo.desktop.icons.getRows()-1;
                                u = i-1;
                            } else {
                                v = j-1;
                            }
                            albireo.desktop.icons.set(albireo.desktop.icons.get(u,v),i,j);
                            i = u;
                            j = v;
                        }
                    }

                    albireo.desktop.icons.set(icon,left,top);
                    albireo.desktop.icons.draw();
                }
            });
        },
		
        setColor : function ( color ) {
            $("body").css("backgroundColor", color);
        }
    },
    ////////////////////////////////// DESKTOP END ////////////////////////////////////////////////////
	
    ////////////////////////////////// ICONS //////////////////////////////////////////////////////////
    "icons" : function (element,width,height) {
        this.width = width;
        this.height = height;
        this.element = element;
        this.rows = null;
        this.cols = null;
        this.icons = new Array();
        this.getWidth = function () {
            return this.width;
        };
        this.getHeight = function () {
            return this.height;
        };
        this.getRows = function () {
            //return Math.floor($(this.element).height()/this.getHeight());
            return this.rows;
        };
        this.getCols = function () {
            //return Math.floor($(this.element).width()/this.getWidth());
            return this.cols;
        };
        this.setCols = function (cols) {
            this.cols = cols;
        };
        this.setRows = function (rows) {
            this.rows = rows;
        };
        this.create = function() {
            for (var i = 0; i < this.getCols(); i++) {
                this.icons[i] = new Array(this.getRows());
                for (var j = 0; j < this.getRows(); j++) {
                    this.set(null,i,j);
                }
            }
        };
        this.draw = function () {
            helper = this;
            this.element.find(".albireoicon").remove();
            for (var i = 0; i < this.getCols();i++) {
                for (var j = 0; j < this.getRows(); j++) {
                    if (this.get(i,j) != null) {
                        this.get(i,j).element = $('<div class="albireoicon"></div>').appendTo(this.element).css(
                        {
                            top: j*this.getHeight(),
                            left: i*this.getWidth(),
                            width: this.getWidth(),
                            height: this.getHeight()
                        }).html('<img src="'+this.get(i,j).image+'" class="iconimage" /><div class="iconName">'+this.get(i,j).name+'</div>')
                        .bind('dblclick', this.get(i,j).application);
                    }
                }
            }

            this.element.selectable({
                distance: 5
            });

            this.element.find(".albireoicon").draggable(
            {
                //containment: this.element.attr("id"),
                containment: albireo.desktop.getElement(),
                distance: 5,
                scroll: false,
                helper: 'clone',
                opacity: 0.5

            });
            this.element.find(".albireoicon").mousedown(function (e) {
                if (!albireo.keys.ctrl) {
                    $("#" + helper.element.attr("id") + " > .ui-selected").removeClass('ui-selected');
                }
                $(this).addClass('ui-selected');
                e.stopPropagation();
            });
			
        };
        this.set = function (icon,left,top) {
            this.icons[left][top] = icon;
        };
        this.get = function (left,top) {
            return this.icons[left][top];
        };
    },
    ////////////////////////////////// ICONS END //////////////////////////////////////////////////////
	
    ////////////////////////////////// IMAGE //////////////////////////////////////////////////////////
    "image" : {
        resize : function ( image, element ) {
            proportions = {
                width : image.width,
                height: image.height
            };
			
            if ( element.width() < image.width ) {
                proportions.width = element.width();
                proportions.height = (element.width() / image.width) * image.height;
            }
			
            if ( element.height() < image.height ) {
                proportions.height = element.height();
                proportions.width = (element.height() / image.height) * image.width;
            }
            return proportions;
        },
		
        center : function (innerW, innerH, outerW, outerH) {
            return {
                left: (outerW - innerW) / 2,
                top: (outerH - innerH) / 2
            };
        },
        
        stretch : function ( image, element ) {
            image.width = element.width();
            image.height = element.height();
        }
    },
	
    ////////////////////////////////// IMAGE END //////////////////////////////////////////////////////
	
    ////////////////////////////////// ICON CONSTRUCTOR ///////////////////////////////////////////////
    "icon" : function (image,name,url) {
        this.name = name;
        this.url = url;
        this.title = null;
        this.image = image;
        this.element = null;
        //this.application = application;
	
        this.getName = function () {
            return this.name;
        };
	
        this.setName = function (name) {
            this.name = name;
        };
		
        this.getTitle = function () {
            return this.title;
        };
	
        this.setTitle = function (title) {
            this.title = title;
        };
	
        this.getImage = function () {
            return this.image;
        };
	
        this.setImage = function (image) {
            this.image = image;
        };
	
        //this.getApplication = function () {
            //return this.application;
        //};
	
        //this.setApplication = function (application) {
            //this.application = application;
        //};
    },
	
    "contextmenu" : function (id) {
        var self = this;
        id.bind("contextmenu", function(e) {
            self.draw(e);
            e.preventDefault();
        });
        this.list = new Array();

        this.getList = function () {
            return this.list;
        };
	
        this.fill = function (list) {
            this.list = list;
        };
		
        this.add = function (name, callback) {
            this.list.push({
                "name" : name,
                "callback" : callback
            });
        };
	
        this.draw = function (event) {
            $("#contextmenu").html("");
            list = this.getList();
            for (var item in list) {
                $("<div class='contextmenuitem'>"+list[item].name+"</div>").click(list[item].callback).appendTo("#contextmenu");
            }
            left = event.pageX;
            mytop = event.pageY;
            left = Math.min(($(window).width()-20)- $("#contextmenu").width(), left);
            mytop = Math.min(($(window).height()-20) - $("#contextmenu").height(), mytop);
            $("#contextmenu").css({
                "top" : mytop,
                "left": left,
                "zIndex": 100000
            });
            $("#contextmenu").show();
            help = this;
            $("#contextmenu").bind("clickoutside", function () {
                help.hide();
                $("#contextmenu").unbind("clickoutside");
            });
        };
		
        this.hide = function() {
            $("#contextmenu").hide();
        };
    },
    ////////////////////////////////// ICON CONSTRUCTOR END ///////////////////////////////////////////
	
    ////////////////////////////////// KEYBOARD INPUT /////////////////////////////////////////////////
    "keys" : {
        "ctrl" : false,
        "init" : function() {
            $(document).keydown(
                function(event) {
                    if (event.ctrlKey) {
                        albireo.keys.ctrl = true;
                    }
                }
                ).keyup(
                function(event) {
                    if (event.which == 17) {
                        albireo.keys.ctrl = false;
                    }
                }
                );
        }
    },
    ////////////////////////////////// KEYBOARD INPUT END /////////////////////////////////////////////
	
    "taskbar" : {
        "element" : null,
        "setElement" : function (element) {
            albireo.taskbar.element = element;
        },
        "getElement" : function () {
            return albireo.taskbar.element;
        },
        "start" : {
            "element": null,
            "image" : null,
            "caption" : null,
            "getElement" : function () {
                return albireo.taskbar.start.element;
            },
            "setElement" : function (element) {
                albireo.taskbar.start.element = element;
            },
            "getImage" : function () {
                return albireo.taskbar.start.image;
            },
            "setImage" : function (image) {
                albireo.taskbar.start.image = image;
            },
            "getCaption" : function () {
                return albireo.taskbar.start.caption;
            },
            "setCaption" : function (caption) {
                albireo.taskbar.start.caption = caption;
            },
            "draw" : function () {
                id = albireo.taskbar.start.getElement();
                id.html(
                    albireo.taskbar.start.getImage() ? "<div id='taskbarstartimage'><img src='"+albireo.taskbar.start.getImage()+"' alt='start image'/></div>" : "" +
                    albireo.taskbar.start.getCaption() ? "<div id='taskbarstartcaption'>"+albireo.taskbar.start.getCaption()+"</div>" : ""
                    ).click(albireo.taskbar.startmenu.draw);
            }
        },
        "init" : function () {
            albireo.taskbar.setElement($("#taskbar"));
            albireo.taskbar.startmenu.setElement($("#albireostartmenu"));

            //testovacie polozky pre startmenu
            //prvkom nie je priradena ziadna akcia na kliknutie
            var subsubitem2 = new albireo.taskbar.startmenu.item(new albireo.icon(function () {
                albireo.applications.createFromUrl("Seznam","http://www.seznam.cz");
            },"http://www.veryicon.com/icon/preview/System/Systematrix%20Full/Internet%20Icon.jpg","subsubB"),[]);

            var subsubitem22 = new albireo.taskbar.startmenu.item(new albireo.icon(function () {
                albireo.applications.createFromUrl("Seznam","http://www.seznam.cz");
            },"http://www.veryicon.com/icon/preview/System/Systematrix%20Full/Internet%20Icon.jpg","subsubB2"),[]);

            var subsubitem = new albireo.taskbar.startmenu.item(new albireo.icon(function () {
                albireo.applications.createFromUrl("Seznam","http://www.seznam.cz");
            },"http://www.veryicon.com/icon/preview/System/Systematrix%20Full/Internet%20Icon.jpg","subsubA"),[]);

            var subitem = new albireo.taskbar.startmenu.item(new albireo.icon(function () {
                albireo.applications.createFromUrl("Seznam","http://www.seznam.cz");
            },"http://www.veryicon.com/icon/preview/System/Systematrix%20Full/Internet%20Icon.jpg","subA"),[subsubitem]);

            var subitem2 = new albireo.taskbar.startmenu.item(new albireo.icon(function () {
                albireo.applications.createFromUrl("Seznam","http://www.seznam.cz");
            },"http://www.veryicon.com/icon/preview/System/Systematrix%20Full/Internet%20Icon.jpg","subB"),[subsubitem2]);

            var subitem22 = new albireo.taskbar.startmenu.item(new albireo.icon(function () {
                albireo.applications.createFromUrl("Seznam","http://www.seznam.cz");
            },"http://www.veryicon.com/icon/preview/System/Systematrix%20Full/Internet%20Icon.jpg","subB2"),[subsubitem22]);

            var item = new albireo.taskbar.startmenu.item(new albireo.icon(function () {
                albireo.applications.createFromUrl("Seznam","http://www.seznam.cz");
            },"http://www.veryicon.com/icon/preview/System/Systematrix%20Full/Internet%20Icon.jpg","A"),[subitem]);

            var item2 = new albireo.taskbar.startmenu.item(new albireo.icon(function () {
                albireo.applications.createFromUrl("Seznam","http://www.seznam.cz");
            },"http://www.veryicon.com/icon/preview/System/Systematrix%20Full/Internet%20Icon.jpg","B"),[subitem2,subitem22]);

            albireo.taskbar.startmenu.addItem(item);
            albireo.taskbar.startmenu.addItem(item2);

            albireo.taskbar.start.setElement($("#startbutton"));
            albireo.taskbar.start.setCaption("Start");
            albireo.taskbar.start.setImage("css/skins/albireosilver/logo.png");

            albireo.taskbar.applications.setElement($("#applications"));

            //TODO prerobit clocks na tray-application zrusit gadgety
            var clocks = new albireo.taskbar.systemtray.systemtrayGadget({

                "init" : function() {
                    var systemtray = albireo.taskbar.systemtray.getElement();
                    var drawn;

                    systemtray.append("<div type='text' id='datepicker'></div>");
                    $("#datepicker").datepicker();
                    $("#ui-datepicker-div").remove();
                    calendar = $("#datepicker");

                    $("<div id='clocks' class='systemtray-gadget'></div>")
                    .appendTo(systemtray)
                    .mouseover(function(){
                        $(this).css('cursor','pointer');
                    })
                    .click(function () {
                        //event.preventDefault();
                        calendar.show();
                        drawn = true;
                        calendar.bind("clickoutside", function () {
                            if(!drawn) {
                                calendar.hide();
                                calendar.unbind("clickoutside");
                            }
                            drawn = false;
                        });
                    });

                    $(calendar).click(function(){
                        drawn=true;
                    });

                    $("#clocks").append("<div id='time'></div>");
                    $("#clocks").append("<div id='date'></div>");
                    this.execute();
                },

                "execute" : function() {
                    function repeat() {
                        now = new Date();
                        hours = now.getHours()<10 ? "0" : "";
                        minutes = now.getMinutes()<10 ? "0" : "";
                        //seconds = now.getSeconds()<10 ? "0" : "";
                        month = now.getMonth()+1;

                        $("#time").html(hours+now.getHours()+":"+minutes+now.getMinutes());//+":"+seconds+now.getSeconds());
                        $("#date").html(now.getDate()+"."+month+"."+now.getFullYear());

                        setTimeout(repeat,1000);
                    }
                    repeat();
                }
            },"Clocks");

            //TODO hiddenApps div grafika zalamovanie, pretekanie ikoniek
            var trayArrow = {
                "execute" : function(trayElement) {
                    var systemtray = albireo.taskbar.systemtray.getElement();

                    hiddenApps = $("<div id='hiddenApps'></div>");
                    hiddenApps.appendTo(systemtray)
                    .mouseover(function(){
                        $(this).css('cursor','pointer');
                    });

                    trayElement
                    .click(function () {
                        hiddenApps.show();
                        var drawn = true;
                        hiddenApps.bind("clickoutside", function () {
                            if(!drawn) {
                                hiddenApps.hide();
                                hiddenApps.unbind("clickoutside");
                            }
                            drawn = false;
                        });
                    });

                    trayArrow.manageIcons();

                    contextmenu = new albireo.contextmenu(trayElement);
                    contextmenu.add("Sipka prva polozka", function () {
                        alert("sipka jedna");
                    });
                    contextmenu.add("Sipka druha polozka", function () {
                        alert("sipka dva");
                    });
                },

                "manageIcons" : function() {
                    var applications = albireo.taskbar.systemtray.getApplications();
                    hiddenApps = $("#hiddenApps");
                    numberToShow = 4;
                    if(applications.length > numberToShow) {
                        appsToMove = applications.length - numberToShow;
                        for (var i = 0;i<appsToMove;i++)
                        {
                            name = applications[i].getName();
                            element = $("#" + name);
                            $("#hiddenApps").append(element);
                        }
                    }
                }
            };

            //Testovacia aplikacie pre ikonky v system tray
            //aplikacia prida kazdej ikonke default funkciu otvarania startmenu
            var systemTrayTestApp = {
                "execute" : function(trayElement) {
                    firstClick = false;
                    trayElement.click(function(){
                        if(!firstClick) {
                            alert("Toto je test, kliknutim na ikonku otvorite start.\n Dalsim klikom start zmizne.");
                            firstClick = true;
                        }
                    });
                    contextmenu = new albireo.contextmenu(trayElement);
                    contextmenu.add("Ikonky prva polozka", function () {
                        alert("ikonky jedna");
                    });
                    contextmenu.add("Ikonky druha polozka", function () {
                        alert("ikonky dva");
                    });
                }
            };

            albireo.taskbar.systemtray.setElement($("#systemtray"));
            albireo.taskbar.systemtray.addGadget(clocks);

            //testovacie polozky pre system tray
            //akcia ktora sa vykonava po kliknuti na testovacie ikonky je hidnutie nasledujucej ikonky
            albireo.taskbar.systemtray.addApplication(new albireo.taskbar.systemtray.systemtrayApplication
                (systemTrayTestApp.execute,"Albireo","albireostartmenu","css/skins/albireosilver/logo.png"));
            albireo.taskbar.systemtray.addApplication(new albireo.taskbar.systemtray.systemtrayApplication
                (systemTrayTestApp.execute,"Test","albireostartmenu","images/kernel/users/users.jpg"));
            albireo.taskbar.systemtray.addApplication(new albireo.taskbar.systemtray.systemtrayApplication
                (systemTrayTestApp.execute,"Users","albireostartmenu","images/kernel/users/roles.jpg"));
            albireo.taskbar.systemtray.addApplication(new albireo.taskbar.systemtray.systemtrayApplication
                (systemTrayTestApp.execute,"Users2","albireostartmenu","images/kernel/default.jpg"));
            albireo.taskbar.systemtray.addApplication(new albireo.taskbar.systemtray.systemtrayApplication
                (systemTrayTestApp.execute,"Users3","albireostartmenu","images/kernel/logo-red.png"));
            albireo.taskbar.systemtray.addApplication(new albireo.taskbar.systemtray.systemtrayApplication
                (systemTrayTestApp.execute,"Albireo","albireostartmenu","css/skins/albireosilver/gmail-icon256.png"));
            albireo.taskbar.systemtray.addApplication(new albireo.taskbar.systemtray.systemtrayApplication
                (systemTrayTestApp.execute,"Albireo","albireostartmenu","css/skins/albireosilver/Google Docs logo_002.png"));
            albireo.taskbar.systemtray.addApplication(new albireo.taskbar.systemtray.systemtrayApplication
                (systemTrayTestApp.execute,"Albireo","albireostartmenu","css/skins/albireosilver/Settings-icon.png"));
            albireo.taskbar.systemtray.addApplication(new albireo.taskbar.systemtray.systemtrayApplication
                (trayArrow.execute,"trayArrow","hiddenApps","css/skins/albireosilver/arrow.png")); //arrow

            albireo.taskbar.draw();
        },
        "startmenu" : {
            "element" : null,
            "menuItems" : [],
            "item" : function(icon, subItems){
                this.icon = icon,
                this.subItems = subItems;

                this.getIcon = function() {
                    return this.icon;
                };

                this.getSubItems = function() {
                    return this.subItems;
                };
                //TODO rebuild id assigning
                //TODO remove draw and drawSub
                this.drawSubMenu = function(topPosition, leftPosition, parentId) {
                    if(subItems.length > 0){
                        var menu = $("<div ></div>")
                        .appendTo("#"+ parentId)
                        .addClass("albireostartmenu-submenu");
                        menu.attr('Id', parentId + "menu");
                        menu.css({
                            position: "absolute",
                            left: (leftPosition),
                            top: (topPosition)
                        });
                        $("#"+parentId).hover(function() {
                            menu.stop(true,true).fadeIn("slow");
                            $("#"+parentId).css({
                                backgroundColor: "#D3D3D4"
                            });
                        },
                        function(){
                            menu.stop(true,true).fadeOut("slow");
                            $("#"+parentId).css({
                                backgroundColor: "transparent"
                            });
                        });
                    } else {
                        $("#"+parentId).mouseover(function() {
                            $("#"+parentId).css({
                                backgroundColor: "#D3D3D4"
                            });
                        })
                        .mouseout(function(){
                            $("#"+parentId).css({
                                backgroundColor: "transparent"
                            });
                        });
                    }
                    for (var item in subItems) {
                        var currItem = subItems[item];
                        menuItem = $("<div>" + currItem.getIcon().getName() + "</div>")
                        .addClass("albireostartmenu-item")
                        .appendTo(menu);
                        menuItem.attr('id', currItem.getIcon().getName());
                        //TODO item*30 should be replaced by dependence on curent menuitem height
                        //v novom jQuery funguje, treba prepisat :)
                        currItem.drawSubMenu((item)*30 -1, menu.width(), currItem.getIcon().getName());
                    }
                };
            },
            "removeItem" : function (item, items) {
                albireo.arrays.remove(item, items);
            },
            "getItems" : function() {
                return albireo.taskbar.startmenu.menuItems;
            },
            "getElement" : function () {
                return albireo.taskbar.startmenu.element;
            },
            "setElement" : function (element) {
                albireo.taskbar.startmenu.element = element;
            },
            "addItem" : function (item) {
                albireo.taskbar.startmenu.menuItems.push(item);
            },
            "hide" : function () {
                albireo.taskbar.startmenu.getElement().hide();
            },
            "modelHtml" : function () {
                albireo.taskbar.startmenu.drawSub(albireo.taskbar.startmenu.getItems(), albireo.taskbar.startmenu.getElement());
            },
            "draw" : function () {
                id = albireo.taskbar.startmenu.getElement();
                id.show();
                var drawn = true;
                id.bind("clickoutside", function () {
                    if (!drawn) {
                        id.hide();
                        id.unbind("clickoutside");
                    }
                    drawn = false;
                });
            },
            "drawSub" : function (items, id) {
                for (var item in items) {
                    currItem = items[item];
                    menuItem = $("<div id="+ currItem.getIcon().getName() +">"+currItem.getIcon().getName()+"</div>")
                    .addClass("albireostartmenu-item")
                    .appendTo(id);
                    //TODO item*30 should be replaced by dependence on curent menuitem height
                    currItem.drawSubMenu((item)*30 -1, id.width(), currItem.getIcon().getName());
                }
            }
        },
        "applications" : {
            "element" : null,
            "items" : [],
            "getElement" : function () {
                return albireo.taskbar.applications.element;
            },
            "setElement" : function (element) {
                albireo.taskbar.applications.element = element;
            },
            "getItems" : function () {
                return albireo.taskbar.applications.items;
            },
            "addItem" : function (item) {
                albireo.taskbar.applications.items.push(item);
            },
            "removeItem" : function (item) {
                albireo.arrays.remove(item, albireo.taskbar.applications.items);
            },
            "create" : function (process) {
                if (process.isWindowed()) {
                    albireo.taskbar.applications.addItem(process);
                    albireo.taskbar.applications.draw();
                }
            },
            "close" : function (process) {
                if (process.isWindowed()) {
                    albireo.taskbar.applications.removeItem(process);
                    albireo.taskbar.applications.draw();
                }
            },
            "draw" : function() {
                var applications;
                applications = albireo.taskbar.applications.getElement();
                applications.html("");
                for (var item in items = albireo.taskbar.applications.getItems()) {
                    currItem = items[item];
                    $("<div>"+currItem.getName()+"</div>")
                    .addClass("taskbar-application")
                    .appendTo(applications)
                    .click(
                        currItem.toggle
                        );
                }
            }
        },
        "systemtray" : {
            "element" : null,
            "gadgets" : [],
            "applications" : [],
            "systemtrayGadget" : function(gadget, name){
                this.gadget = gadget,
                this.name = name;

                this.getGadget = function() {
                    return this.gadget;
                };

                this.getName = function() {
                    return this.name;
                };

                this.init = function() {
                    gadget.init();
                };
            },

            "systemtrayApplication" : function(callback, name, elementId, icon){//execute, meno, ID elementu okna aplikacie, obrazok ikonky
                this.execute = callback,//callback - optional special operations for left and right click
                this.name = name;
                this.elementId = elementId;
                this.icon = icon;

                this.getGadget = function() {
                    return this.gadget;
                };

                this.getName = function() {
                    return this.name;
                };

                this.getExecute = function() {
                    return this.execute;
                };

                this.getElement = function() {
                    return this.element;
                };

                //TODO sirka a velkost do div namiesto img
                this.init = function() {
                    var systemtray = albireo.taskbar.systemtray.getElement();
                    
                    trayElement = $("<div id='"+name+"' class='systemtray-application' shown='true'></div>")
                    .append("<img src='" + icon + "' alt='" + name + "' width='24' height='24' class='systemtray-img'></img>"); //veľkosť ikon v tray (aj šípka)..pozícia je fixná a nezávyslá na šírke či výške ikony..neberie class
                    trayElement.appendTo(systemtray);
                    trayElement.mouseover(function(){
                        $(this).css('cursor','pointer');
                    });
                    trayElement.click(function () {
                        if ($(this).attr("shown")=="true") {
                            $("#" + elementId).hide();
                            $(this).attr("shown","false");
                        } else {
                            $("#" + elementId).show();
                            $(this).attr("shown","true");
                        }
                    });
                    this.execute(trayElement);
                };
            },
            "getElement" : function () {
                return albireo.taskbar.systemtray.element;
            },
            "setElement" : function (element) {
                albireo.taskbar.systemtray.element = element;
            },
            "getGadgets" : function () {
                return albireo.taskbar.systemtray.gadgets;
            },
            "getApplications" : function () {
                return albireo.taskbar.systemtray.applications;
            },
            "addGadget" : function (item) {
                albireo.taskbar.systemtray.gadgets.push(item);
            },
            "addApplication" : function (item) {
                albireo.taskbar.systemtray.applications.push(item);
            },
            "removeGadget" : function (item) {
                albireo.arrays.remove(item, albireo.taskbar.systemtray.gadgets);
            },
            "removeApplication" : function (item) {
                albireo.arrays.remove(item, albireo.taskbar.systemtray.applications);
            },
            "draw" : function() {
                var systemtray;
                systemtray = albireo.taskbar.systemtray.getElement();
                systemtray.html("");
                for (var gadget in gadgets = albireo.taskbar.systemtray.getGadgets()) {
                    currItem = gadgets[gadget];
                    currItem.init();
                }
                var applications = albireo.taskbar.systemtray.getApplications();
                for (var application in applications) {
                    currItem = applications[application];
                    currItem.init();
                }
            }
        },
        "draw" : function () {
            albireo.taskbar.start.draw();
            albireo.taskbar.systemtray.draw();
        }
    },
	
    applications : {
        APPLICATION : "application",
        pid : 0,
        processes : [],
        listeners : [],
        focus: null,
        moveToVisible : function () {
            if ($(".ui-dialog").position().top < 0 ) {
                $(".ui-dialog").css(top, 0);
            }
        //console.log nefunguje pre IE, pouzivat pre debug iba vo FF Chrome Opera Safari
        //console.log($(".ui-dialog").position().top);
            
        /*for (var app in albireo.applications.processes) {
                application = albireo.applications.processes[app];
                if (application.isWindowed()) {
                    if ($("#"+albireo.applications.APPLICATION+application.getId()).position().left < 0 ) {
                        $("#"+albireo.applications.APPLICATION+application.getId()).css("left", 0);
                    }
                    alert($("#"+albireo.applications.APPLICATION+application.getId()).position().top);
                    if ($("#"+albireo.applications.APPLICATION+application.getId()).position().top < 0 ) {
                       $("#"+albireo.applications.APPLICATION+application.getId()).css("top", 0);
                    }
                }
            }*/
        },
        kill : function (process) {
            $("#"+albireo.applications.APPLICATION+process.getId()).remove();
            albireo.arrays.remove(process,albireo.applications.processes);
        },
        setFocus : function (process) {
            if (process == null) {
                albireo.applications.focus = null;
                return;
            }
            if(process.isWindowed()){
                albireo.applications.focus = process;
            }
        },
        addAppListener : function (listener) {
            albireo.applications.listeners.push(listener);
        },
        removeAppListener : function (listener) {
            albireo.arrays.remove(listener, albireo.applications.listeners);
        },
        addProcess : function (process) {
            albireo.applications.processes.push(process);
        },
        removeProcess : function (process) {
            albireo.arrays.remove(process, albireo.applications.processes);
        },
        create : function (name, windowed) {
            if (!windowed) {
                windowed = false;
            }
            process = new albireo.applications.process(albireo.applications.newPid());
            process.setName(name);
            process.setWindowed(windowed);
            albireo.applications.addProcess(process);
            for (var listener in albireo.applications.listeners) {
                albireo.applications.listeners[listener].create(process);
            }
            return process;
        },
        createWindow : function (name,content,options) {
            if (options == undefined) {
                options = {};
            }
            options.maximized = (options.maximized === true);
            
            var process = albireo.applications.create(name,true);         
            var focusStartHandler = function (){
                $("<div id=desktopOverlay></div>").appendTo("body")
                .css({
                    width : $("body").css("width"),
                    height: $("body").css("height"),
                    zIndex : "10000",
                    position: "absolute",
                    left:"0",
                    top :"0"
                });
            //                    $("div[aria-labelledby=ui-dialog-title-"+albireo.applications.APPLICATION+process.getId()+"]").css({
            //                        zIndex : "1499"
            //                    });
            //                    $("#desktopOverlay").html(albireo.applications.APPLICATION+process.getId());
            };
            var focusStopHandler = function() {
                $("#desktopOverlay").remove();
            //                    $("div[aria-labelledby=ui-dialog-title-"+albireo.applications.APPLICATION+process.getId()+"]").appendTo("body").css({
            //                        zIndex : "1001"
            //                    });
            };

            var app = $("<div id='"+albireo.applications.APPLICATION+process.getId()+"' class='dialogApplication' title='"+name+"'>"+content+"</div>").appendTo($("#desktop"))
            .dialog(
            {
                maximizable: true,
                minimizable: true,
                maximized: options.maximized,
                //TODO: ADD users before close to handle close button (for saving and so on) event listener
                focus: process.focus,
                close: process.close,

                dragStart: function() {
                    focusStartHandler();
                },
                dragStop: function() {
                    focusStopHandler();
                },
                resize: function () {
                    $(this).find('.resizable').width($(this).width()).height($(this).height());
                },
                resizeStart: function() {
                    focusStartHandler();
                },
                resizeStop: function() {
                    focusStopHandler();
                }
            });
            //TODO dialog on top pri kliku do iframu
            //            app.find("iframe")
            //            .bind('click', function(){
            //                alert("click");
            //                var maxZ = Math.max.apply(null,$.map($('body > *'), function(e,n){
            //                if($(e).css('position')=='absolute')
            //                    return parseInt($(e).css('z-index'))||1 ;
            //                })
            //                );
            //                    alert(maxZ);
            //                $(this).dialog("option","zIndex",maxZ+1);
            //            });
            $('.ui-dialog-titlebar-maxi').click(function() {
                $('#'+albireo.applications.APPLICATION+process.getId()).focus();
            });
            
            $(app).find('.resizable').width($(app).width()).height($(app).height());
            albireo.applications.focused = process;
        },
        createGadget : function (name,content,options) {
            if (options == undefined) {
                options = {};
            }
            process = albireo.applications.create(name);
            process.setWindowed(true);

            //TODO: oklestena verze options - melo by se vytvorit, obecnejsi a nakej obecnej parser kerej bude jen predavat
            var app = $("<div id='"+albireo.applications.APPLICATION+process.getId()+"' title='"+name+"'>"+content+"</div>").appendTo($("body")).draggable().css({
                width: (options.width ? options.width : 177),
                height: (options.height ? options.height : 'auto'),
                position: "absolute",
                left: (options.position ? options.position.left : 100),
                top: (options.position ? options.position.top : 0)
            //backgroundColor: "#fff"
            }).resizable({
                resize: function () {
                    $(this).find('.resizable').width($(this).width()-5).height($(this).height()-5);
                }
            });
            //alert($(app).find('.resizable').attr('src'));
            $(app).find('.resizable').width($(app).width()-5).height($(app).height()-5);

            $("<a href='#' class='ui-dialog-titlebar-close'><span class='ui-icon ui-icon-closethick'></a>").bind( 'click', process.close ).css({
                position: "absolute",
                display: "block",
                "float":"right",
                backgroundColor: "#bbb",
                right: 0,
                top: 0,
                width: "16px"
            }).appendTo(app);

        //app.hover(function() { closeButton.prependTo(app); }, function () { closeButton.remove(); });
        },
        createFromHtml : function(name,html,options) {
            albireo.applications.createWindow(name,html,options);
        },
        createFromUrl : function(name,url,options) {
            albireo.applications.createFromHtml(name,"<iframe src='"+url+"' class='resizable' />",options);
        },
        resize : function (app) {
        //TODO: after presentation
        },
        //TODO: temporary solution!
        process : function (id) {
            this.id = id;
            this.name = null;
            this.windowed = false;
            this.focus = false;
            var self = this;
			
            this.equals = function(process) {
                //TODO: should take care that object is really process type - better type recognition
                if (process == null ) return false;
                if (this.getId() === process.getId()) {
                    return true;
                }
                return false;
            };
	
            this.getId = function () {
                return this.id;
            };
		
            this.getName = function () {
                return this.name;
            };
	
            this.setName = function (name) {
                this.name = name;
            };
			
            this.isWindowed = function () {
                return this.windowed;
            };
			
            this.setWindowed = function(windowed) {
                this.windowed = windowed;
            };

            //TODO: should this have any application? some of them are not windowed or can be gadgets...
            //Window can  be observer of process
            this.toggle = function () {
                //TODO: shouldnt be done by dialogs attributes??? More information than really needed OR delegation to "Window"
                if (self.isWindowed()) {
                    if (self.equals(albireo.applications.focus)) {
                        $("#"+albireo.applications.APPLICATION+self.getId()).dialog("minimize");
                        albireo.applications.setFocus(null);
                    } else {
                        $("#"+albireo.applications.APPLICATION+self.getId()).dialog("unminimize");
                        albireo.applications.setFocus(self);
                    }
                }
            };

            this.focus = function () {
                albireo.applications.setFocus(self);
            };

            this.close = function() {
                for (var listener in albireo.applications.listeners) {
                    albireo.applications.listeners[listener].close(self);
                }
			
                //TODO: maybe also an observer
                if (self.isWindowed()) {
                    $("#"+albireo.applications.APPLICATION+self.getId()).remove();
                }
                albireo.applications.removeProcess(self);
                //TODO: always return false to prevent link or event stop propagation?
                return false;
            };
        },
        newPid : function () {
            return ++albireo.applications.pid;
        }
    },
    arrays : {
        find : function(what, where) {
            if (what == null) {
                return false;
            }
            for (var i in where) {
                if (what.equals(where[i])) {
                    return i;
                }
            }
            return false;
        },
		
        remove : function(what, where)  {

            which = albireo.arrays.find(what, where);
            if (which) {
                where.splice(which, 1);
            }
        }
    }
};

/**
 * Sets up library and front end
 */
var initfnc = function () {
    $("<div id='loading'><h1>Loading</h1></div>").width($(window).width()).height($(window).height()).css({
        zIndex: 10000,
        position: "absolute",
        backgroundColor: "#fff",
        color: "#000"
    }).appendTo("body")
    .find("h1").css({
        "width" : "200px",
        "margin" : "auto"
    });
    document.onselectstart = function () {
        return false;
    };

    var url = "waterexplosion.jpg";
    albireo.taskbar.init();

    albireo.desktop.setElement($("#desktop"));
    albireo.desktop.setColor("#000");
    albireo.desktop.display(url);
    albireo.desktop.createIcons();

    $("<div id='contextmenu'></div>").appendTo("body").hide();
    albireo.keys.init();
    albireo.applications.addAppListener(albireo.taskbar.applications);

    $(window).resize( function () {
        albireo.desktop.display(url);
    });
    $(window).load( function () {
        $("#loading").remove();
        albireo.taskbar.startmenu.modelHtml();
    });
    
};

$(document).bind('ready', initfnc);
